<template>
  <div>
    <!-- 下单 -->
    <el-card class="card">
      <!-- 步骤 -->
      <el-steps
        style="max-width: 200px; margin: 20px auto"
        :active="active"
        finish-status="success"
      >
        <el-step title="选择服务" />
        <el-step title="订单确定" />
      </el-steps>
      <!-- 老人信息 -->
      <div class="info">
        <div class="order">
          <!-- 头像 -->
          <div class="headImg">
            <img
              :src="
                familyData.photo
                  ? imgUrl + familyData.photo
                  : 'http://123.57.237.81:8080/caresystem/upload/2024/11/21/20241121152950642.jpg'
              "
              alt=""
            />
          </div>
          <div class="orderInfo">
            <div class="txt">
              <div>老人姓名：</div>
              <div>{{ familyData.name! }}</div>
            </div>
            <div class="txt">
              <div>身份证号：</div>
              <div>{{ familyData.idCard! }}</div>
            </div>
          </div>
        </div>
        <!-- 表格 -->
        <div class="family">
          <div class="title" style="width: 14%">家属信息：</div>
          <el-table :data="familyData.family" style="width: 450px">
            <el-table-column prop="name" label="家属姓名" width="180" />
            <el-table-column prop="relation" label="与老人关系" width="180" />
            <el-table-column prop="mobile" label="联系方式" />
          </el-table>
        </div>
      </div>
      <el-form
        v-show="addShow"
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        style="max-width: 400px"
        label-width="auto"
        class="demo-ruleForm"
        status-icon
      >
        <!-- 选择床位 -->
        <div class="header">
          <div class="header_left">
            <span class="line" />
            <span>选择床位</span>
          </div>
          <div>床位费合计:{{ ruleForm.begPrice! * ruleForm.days! }}</div>
        </div>
        <el-form-item label="选择床位：" prop="begId">
          <el-cascader
            v-model="begData"
            :props="props"
            :options="getcounts"
            clearable
            @change="handleChange"
          />
        </el-form-item>
        <el-form-item label="床位单价：" prop="begPrice">
          <el-input-number
            v-model="ruleForm.begPrice!"
            placeholder="200/天"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="入住天数：" prop="days">
          <el-input-number
            v-model="ruleForm.days!"
            placeholder="请输入"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="入住日期：" prop="startDate">
          <el-date-picker
            v-model="ruleForm.startDate"
            type="datetime"
            placeholder="请选择"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <!-- 餐饮膳食 -->
        <div class="header">
          <div class="header_left">
            <span class="line" />
            <span>餐饮膳食</span>
          </div>
          <div>伙食费合计:{{ ruleForm.foodPrice! * ruleForm.days! }}</div>
        </div>
        <el-form-item label="套餐单价：" prop="foodPrice">
          <el-input-number
            v-model="ruleForm.foodPrice!"
            placeholder="25/天"
            controls-position="right"
          />
        </el-form-item>
        <!-- 护理服务 -->
        <div class="header">
          <div class="header_left">
            <span class="line" />
            <span>护理服务</span>
          </div>
          <div>护理费合计:{{ ruleForm.servicePrice! * ruleForm.days! }}</div>
        </div>
        <el-form-item label="护理费：" prop="servicePrice">
          <el-input-number
            v-model="ruleForm.servicePrice!"
            placeholder="100/天"
            controls-position="right"
          />
        </el-form-item>
        <el-button type="primary" @click="add">添加服务</el-button>
        <el-table :data="serviceList" style="width: 450px; color: #000 !important">
          <el-table-column prop="name" label="服务项目" width="180" />
          <el-table-column prop="content" label="服务内容" width="180" />
          <el-table-column prop="mobile" label="合计" />
        </el-table>
        <!-- 其他收费 -->
        <div class="header">
          <div class="header_left">
            <span class="line" />
            <span>其他收费</span>
          </div>
        </div>
        <el-form-item label="押金：" prop="cashPledge">
          <el-input-number
            v-model="ruleForm.cashPledge!"
            placeholder="请输入"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="一次性生活费：" prop="livingPrice">
          <el-input-number
            v-model="ruleForm.livingPrice!"
            placeholder="请输入"
            controls-position="right"
          />
        </el-form-item>
        <!-- 入院费用核定周期设置 -->
        <div class="header">
          <div class="header_left">
            <span class="line" />
            <span>入院费用核定周期设置</span>
          </div>
        </div>
        <el-form-item label="入院费用核定天数" prop="payDays">
          <el-input-number
            v-model="ruleForm.payDays!"
            placeholder="请输入"
            controls-position="right"
          />
        </el-form-item>
        <div class="btns" style="text-align: right">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="save(ruleFormRef)">下一步</el-button>
        </div>
      </el-form>
      <!-- 表格列表 -->
      <Next v-if="!addShow" @close="closeListHandle" />
    </el-card>
    <selectService v-if="dialogVisible" :selectList="serviceList" @close="closeHandle" />
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, provide } from "vue";
import { useRouter, useRoute } from "vue-router";
import { FormInstance, FormRules, UploadProps } from "element-plus";
import { buildingList } from "../../api/config/building/building";
import { buildingListData } from "../../api/config/building/type";
import { houseList } from "../../api/config/house/house";
import selectService from "../../components/market/hospitalized/service/selectService.vue";
import { AddParams } from "../../api/market/hospitalized/type";
import { add as addData, getModel, update } from "../../api/market/hospitalized/hospitalized";
import { buildTree } from "../../utils/treeUtil";
import { ListData } from "../../api/market/service/type";
import { listParams } from "@/api/config/house/type";
import { badListParams } from "@/api/config/bed/type";
import { bedList } from "@/api/config/bed/bed";
import { getElderlyModel } from "@/api/market/elderly/elderly";
import Next from "@/components/market/hospitalized/order/Next.vue";

const route = useRoute();
const router = useRouter();
// 图片根路径
const imgUrl = ref(import.meta.env.VITE_IMG_URL);
//添加显示
const addShow = ref(true);

//步骤条状态 //1为成功
const active = ref(0);
const ruleFormRef = ref();

//新增dialog
let dialogVisible = ref(false);

const ruleForm = reactive<AddParams>({
  elderlyId: 0,
  begId: null,
  begPrice: null,
  days: null,
  startDate: "",
  foodPrice: null,
  servicePrice: null,
  cashPledge: null,
  livingPrice: null,
  payDays: null,
  state: 0,
  services: [],
  files: [],
});
provide("ruleForm", ruleForm);

//关闭列表
const closeListHandle = (data: true) => {
  if (data) {
    addShow.value = true;
    active.value = 0;
  }
};
if (route.query.oldId) ruleForm.elderlyId = Number(route.query.oldId);

//规则
const rules = reactive<FormRules<AddParams>>({
  begId: [
    {
      required: true,
      message: "请选择床位",
      trigger: "change",
    },
  ],
  begPrice: [{ required: true, message: "请输入床位单价", trigger: "blur" }],
  days: [{ required: true, message: "请输入入住天数", trigger: "blur" }],
  startDate: [
    {
      required: true,
      message: "请选择入住日期",
      trigger: "change",
    },
  ],
  foodPrice: [{ required: true, message: "请输入套餐单价", trigger: "blur" }],
  servicePrice: [{ required: true, message: "请输入护理单价", trigger: "blur" }],
  cashPledge: [{ required: true, message: "请输入押金", trigger: "blur" }],
  livingPrice: [{ required: true, message: "请输入一次性生活费", trigger: "blur" }],
  payDays: [{ required: true, message: "请输入入院费用核定天数", trigger: "blur" }],
});

//添加服务
const add = () => {
  dialogVisible.value = true;
};

//服务列表
let serviceList = ref<any[]>([]);

//关闭添加dialog
const closeHandle = (data: ListData[]) => {
  dialogVisible.value = false;
  if (data) {
    //数组去重
    let arr = Array.from(new Set(data.map((item) => item.id))).map((id) =>
      data.find((item) => item.id === id)
    );
    serviceList.value = arr;
    ruleForm.services = arr.map((item: any) => ({ serviceId: item.id }));
  }
};

//取消
const cancel = () => {
  router.push("/market/hospitalized");
};

const allPrice = ref({
  days: 0, //入住天数
  begPrice: 0, //总床位费
  servicePrice: 0, //护理费
  foodPrice: 0, //膳食费
  cashPledge: 0, //押金
  livingPrice: 0, //一次性生活费
  payDays: 0, //核定天数
});
provide("allPrice", allPrice);

//下一步
const save = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      //改变步骤条状态
      active.value = 1;
      //切换列表页
      addShow.value = false;

      // 更新 allPrice 的值
      allPrice.value.days = ruleForm.days!;
      allPrice.value.begPrice = ruleForm.days! * ruleForm.begPrice!;
      allPrice.value.servicePrice = ruleForm.days! * ruleForm.servicePrice!;
      allPrice.value.foodPrice = ruleForm.days! * ruleForm.foodPrice!;
      allPrice.value.cashPledge = ruleForm.days! * ruleForm.cashPledge!;
      allPrice.value.livingPrice = ruleForm.days! * ruleForm.livingPrice!;
      allPrice.value.payDays = ruleForm.payDays!;
    } else {
      // 错误处理
    }
  });
};

//级联选择器格式转换
const props = { label: "name", value: "id" };

// 楼栋列表
const buildList = ref<buildingListData[]>([]);
const getBuildingList = async () => {
  let res = await buildingList();
  buildList.value = res.list;
  getHouseList();
};

//房间列表
const houseParams = reactive<listParams>({
  page: 1,
  pageSize: 1000,
  name: "",
  buildingId: undefined,
});
const house_list = ref<any[]>([]);
const getHouseList = async () => {
  let res = await houseList(houseParams);
  house_list.value = res.list.map((item) => ({
    id: item.id,
    name: item.name,
    pid: item.buildingId,
  }));
  getBedList();
};
//床位
const bedParams = reactive<badListParams>({
  houseId: undefined,
  page: 1,
  pageSize: 1000,
});
const bedListData = ref<any>([]);
const getBedList = async () => {
  let res = await bedList(bedParams);
  bedListData.value = res.list.map((item) => ({
    id: item.id,
    name: item.name,
    pid: item.houseId,
  }));
  mergeData([...buildList.value, ...house_list.value, ...bedListData.value]);
};

let begData: any = ref();
//选择床位
const handleChange = (data: any) => {
  if (data) {
    bedParams.houseId = data[data.length - 1];
    ruleForm.begId = data[data.length - 1];
    getBedList();
  }
};

// 合并
const getcounts = ref([]);
const mergeData = (data: any) => {
  getcounts.value = buildTree(data);
};

//获取详情
const getDetail = async (id: number) => {
  let res = await getModel(id);

  Object.assign(ruleForm, res);
  //床位
  begData = res.begId;
  if (res.services) {
    let data = res.services.map((item) => ({
      id: item.id,
      companyId: 0,
      name: item.serviceName,
      content: item.serviceContent,
    }));
    serviceList.value = data as ListData[];
    //图片
  }
};
interface ElderlyData {
  photo?: string;
  name?: string;
  idCard?: string;
  family?: [];
}
//老人信息
const familyData = reactive<ElderlyData>({});
//获取老人详情
const getElderlyDetail = async (id: number) => {
  let res = await getElderlyModel(id);
  // console.log("888res", res);
  Object.assign(familyData, res);
};
onMounted(() => {
  getBuildingList();
  if (route.query.oldId) {
    getElderlyDetail(Number(route.query.oldId));
  }
  if (route.query.ids) {
    getDetail(Number(route.query.ids));
  }
});
</script>

<style scoped lang="less">
@import url("../../assets/css/hospitalized/order/order.less");
</style>
